package core;

import annotation.Bean;
import annotation.Configuration;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class MyApplicationContext {

    private final Map<String, Object> beanFactory = new HashMap<>();

    public MyApplicationContext(Class<?> configClass) {
        if (configClass.isAnnotationPresent(Configuration.class)) {
            try {
                Object configInstance = configClass.newInstance();

                Method[] methods = configClass.getDeclaredMethods();
                for (Method method : methods) {
                    if (method.isAnnotationPresent(Bean.class)) {
                        String beanName = method.getName();
                        Object beanInstance = method.invoke(configInstance);
                        beanFactory.put(beanName, beanInstance);
                        System.out.println("📦 注册Bean: " + beanName + " -> " + beanInstance.getClass().getSimpleName());
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            throw new RuntimeException("传入的类必须标注 @Configuration");
        }
    }

    public <T> T getBean(String name) {
        return (T) beanFactory.get(name);
    }

    public <T> T getBean(Class<T> clazz) {
        for (Object bean : beanFactory.values()) {
            if (clazz.isInstance(bean)) {
                return (T) bean;
            }
        }
        throw new RuntimeException("找不到类型为 " + clazz.getSimpleName() + " 的Bean");
    }
}